package com.lily.aidouzixun.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Base64;

import com.lily.aidouzixun.bean.UserInfo;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;


/**
 * SharedPreference工具类
 */
public class MySharedPreferences {

    private static final String SHAREDPREFERENCES_NAME = "lily";
    private static volatile  MySharedPreferences instance;

    private MySharedPreferences() {
    }

    /**
     * 得到实例
     * @return
     */
    public static MySharedPreferences getInstance() {
        if(instance == null) {
            synchronized (MyConstant.class) {
                if(instance == null) {
                    instance = new MySharedPreferences();
                }
            }
        }
        return instance;
    }

    /**
     * 设置是否需要刷新动态
     * @param context
     */
    public void setNeedRefreshDynamic(Context context, boolean need) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE );
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean("NeedRefreshDynamic", need);
        editor.commit();
    }

    /**
     * 得到是否需要刷新动态
     * @param context
     * @return
     */
    public boolean getNeedRefreshDynamic(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE );
        return preferences.getBoolean("NeedRefreshDynamic", false);
    }

    /**
     * 设置用户id
     * @param context
     */
    public void setUserId(Context context, String userId) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE );
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("urid", userId);
        editor.commit();
    }

    /**
     * 得到用户名id,如果没有用户名，返回""
     * @param context
     * @return
     */
    public String getUserId(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE );
        String urid = preferences.getString("urid", "");
        if (!Validator.isEffective(urid)) {
            UserInfo userInfo = getUserInfo(context);
            if (userInfo != null) {
                urid = userInfo.getUrid();
            }
        }
        return urid;
    }

    /**
     * 设置是否已经引导过了，如果是，下次不再引导
     */
    public void setGuided(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE );
        SharedPreferences.Editor editor = preferences.edit();
        //存入数据
        editor.putBoolean("isFirstIn", false);
        //提交数据
        editor.commit();
    }

    /**
     * 得到是否已经引导过了
     * @param context
     */
    public boolean getGuided(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
        return preferences.getBoolean("isFirstIn", true);
    }

    /**
     * 设置不再提示更新
     */
    public void setNeverUpdate(Context context, boolean neverUpdate) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE );
        SharedPreferences.Editor editor = preferences.edit();
        //存入数据
        editor.putBoolean("neverUpdate", neverUpdate);
        //提交数据
        editor.commit();
    }

    /**
     * 得到是否设置过不再更新
     * @param context
     */
    public boolean getNeverUpdate(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE );
        return preferences.getBoolean("neverUpdate", false);
    }

    /**
     * 设置用户信息
     * @param context
     */
    public void setUserInfo(Context context, UserInfo userInfo) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE );
        SharedPreferences.Editor editor = preferences.edit();
        if (userInfo != null) {
            //存入数据
            editor.putString("avatar", userInfo.getAvatarUrl());
            editor.putString("urid", userInfo.getUrid());
            editor.putString("username", userInfo.getUsername());
            editor.putString("nickname", userInfo.getNickname());
            editor.putString("email", userInfo.getEmail());
            editor.putString("phone", userInfo.getPhone());
            editor.putString("openid", userInfo.getOpenId());
            editor.putString("loginphone", userInfo.getLoginPhone());
            editor.putInt("loginfrom", userInfo.getLoginFrom());
            editor.putInt("point", userInfo.getPoint());
        } else{
            //存入数据
            editor.putString("avatar", "");
            editor.putString("urid", "");
            editor.putString("username", "");
            editor.putString("nickname", "");
            editor.putString("email", "");
            editor.putString("phone", "");
            editor.putString("openid", "");
            editor.putString("loginphone", "");
            editor.putInt("loginfrom", 0);
            editor.putInt("point", 0);
        }
        //提交数据
        editor.commit();

    }
    /**
     * 得到用户信息
     * @param context
     */
    public UserInfo getUserInfo(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
        String urid = preferences.getString("urid", "");
        if (Validator.isEffective(urid)) {
            UserInfo userInfo = new UserInfo();
            userInfo.setUrid(urid);
            if (Validator.isEffective(preferences.getString("openid", ""))) {
                userInfo.setOpenId(preferences.getString("openid", ""));
            }
            if (Validator.isEffective(preferences.getString("avatar", ""))) {
                userInfo.setAvatarUrl(preferences.getString("avatar", ""));
            }
            if (Validator.isEffective(preferences.getString("username", ""))) {
                userInfo.setUsername(preferences.getString("username", ""));
            }
            if (Validator.isEffective(preferences.getString("nickname", ""))) {
                userInfo.setNickname(preferences.getString("nickname", ""));
            }
            if (Validator.isEffective(preferences.getString("email", ""))) {
                userInfo.setEmail(preferences.getString("email", ""));
            }
            if (Validator.isEffective(preferences.getString("phone", ""))) {
                userInfo.setPhone(preferences.getString("phone", ""));
            }
            if (Validator.isEffective(preferences.getString("loginphone", ""))) {
                userInfo.setLoginPhone(preferences.getString("loginphone", ""));
            }
            if (preferences.getInt("loginfrom", 0) != 0) {
                userInfo.setLoginFrom(preferences.getInt("loginfrom", 0));
            }
            if (preferences.getInt("point", 0) != 0) {
                userInfo.setPoint(preferences.getInt("point", 0));
            }
            return userInfo;
        }
        return null;
    }
    /**
     * 得到发布失败信息
     * @param context
     */
    public String getPublishDiscussFail(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
        String publishDiscuss = preferences.getString("publishdiscuss", "");
        return publishDiscuss;
    }
    /**
     * 设置发布失败信息
     * @param context
     */
    public void setPublishDiscussFail(Context context, String publishDiscuss) {
        SharedPreferences preferences = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE );
        SharedPreferences.Editor editor = preferences.edit();
        //存入数据
        editor.putString("publishdiscuss", publishDiscuss);
        editor.commit();
    }

    /**
     * 根据key和预期的value类型获取value的值
     *
     * @param key
     * @param clazz
     * @return
     */
    public <T> T getValue(Context context, String key, Class<T> clazz) {
        if (context == null) {
            throw new RuntimeException("请先调用带有context，name参数的构造！");
        }
        SharedPreferences sp = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
        return getValue(key, clazz, sp);
    }

    /**
     * 针对复杂类型存储<对象>
     *
     * @param key
     * @param object
     */
    public void setObject(Context context, String key, Object object) {
        SharedPreferences sp = context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream out = null;
        try {

            out = new ObjectOutputStream(baos);
            out.writeObject(object);
            String objectVal = new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT));
            SharedPreferences.Editor editor = sp.edit();
            editor.putString(key, objectVal);
            editor.commit();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @SuppressWarnings("unchecked")
    public <T> T getObject(Context context, String key, Class<T> clazz) {
        SharedPreferences sp =context.getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
        if (sp.contains(key)) {
            String objectVal = sp.getString(key, null);
            byte[] buffer = Base64.decode(objectVal, Base64.DEFAULT);
            ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
            ObjectInputStream ois = null;
            try {
                ois = new ObjectInputStream(bais);
                T t = (T) ois.readObject();
                return t;
            } catch (StreamCorruptedException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (bais != null) {
                        bais.close();
                    }
                    if (ois != null) {
                        ois.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 对于外部不可见的过渡方法
     *
     * @param key
     * @param clazz
     * @param sp
     * @return
     */
    @SuppressWarnings("unchecked")
    private <T> T getValue(String key, Class<T> clazz, SharedPreferences sp) {
        T t;
        try {
            t = clazz.newInstance();
            if (t instanceof Integer) {
                return (T) Integer.valueOf(sp.getInt(key, 0));
            } else if (t instanceof String) {
                return (T) sp.getString(key, "");
            } else if (t instanceof Boolean) {
                return (T) Boolean.valueOf(sp.getBoolean(key, false));
            } else if (t instanceof Long) {
                return (T) Long.valueOf(sp.getLong(key, 0L));
            } else if (t instanceof Float) {
                return (T) Float.valueOf(sp.getFloat(key, 0L));
            }
        } catch (InstantiationException e) {
            e.printStackTrace();
            L.e("system", "类型输入错误或者复杂类型无法解析[" + e.getMessage() + "]");
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            L.e("system", "类型输入错误或者复杂类型无法解析[" + e.getMessage() + "]");
        }
        L.e("system", "无法找到" + key + "对应的值");
        return null;
    }


}
